var patient = {};
var groupVersion = '';
var upf=0;
var mrId='';
var oData;
$(function(){
	$('section#step1').show();
	//加载首页数据上传控件
	$('#medicalRecord_upload_online').uploadifive({
		'uploadScript' : contextPath + '/fileUpload/filesUpload.dhc',
        'height': 32,
        'width' :140 ,
        'auto'  : true ,//是否自动开始
        'uploadLimit' : 100, //一次同步上传的文件数目     
        'fileSizeLimit' : '500MB', //单个文件大小，0为无限制，可接受KB,MB,GB等单位的字符串值     
        'queueSizeLimit' : 100, //队列中同时存在的文件个数限制
        'fileObjName':'file',
        'removeCompleted': true,  //是否完成后移除序列，默认为true
        'removeTimeout' : '3',  //上传完成后队列多长时间后消失。默认 3秒    需要：removeCompleted : true,时使用
        'progressData' :'percentage',//设置上传进度显示方式，percentage显示上传百分比，speed显示上传速度
        'buttonText' : '<i class="fa fa-folder-open fa-lg"></i>&nbsp;&nbsp;选择首页数据',
        'buttonClass': 'uploadifyH5_btn',
        'fileType' : '*.xls; *.xlsx; *.xml; *.dbf',//允许上传的文件格式
        'multi'    : true,//是否支持多文件上传
        'method'   :'post',//提交方式
        'debug':false,
        //当点击文件队列中文件的关闭按钮或点击取消上传时触发
        'onCancel': function(){ },
      	//返回一个错误，选择文件的时候触发  
        'onSelectError':  function(){
        	drgUI.error("文件上传失败！") ;
        },
      	//检测FLASH失败调用  
        'onFallback':function(){  
            drgUI.error("浏览器检测不到兼容版本的HTML5。") ;
        }, 
        'onUploadError' : uploadify_onUploadError,
        'onUpload' : function(){
	        	getMedicalRecordProgress(true);
	     },
        'onQueueComplete':function(queueData) {
        	upf ++ ;
        	drgUI.success("文件上传成功，请点击开始分组！") ;
		}
    }); 
	$('#'+tabId+' #uploadifive-medicalRecord_upload_online-queue').css('display','none');//隐藏进度条
	
	$('div#medicalRecord_upload_online').css('width','');
	$('#medicalRecord_upload_online-button').css({'height':'','line-height':'','width':'150px'}) ;
	// 上传按钮小手悬浮
	$("[type=file]").css("cursor","pointer");
	
	$('#diags .fa-arrow-circle-up,#opers .fa-arrow-circle-up').live('click',function(){
		if($(this).parent().prev()){
			$(this).parent().prev().before($(this).parent());
		}
	});
	$('#diags .fa-arrow-circle-down,#opers .fa-arrow-circle-down').live('click',function(){
		if($(this).parent().next()){
			$(this).parent().next().after($(this).parent());
		}
	});
	$('#diags .fa-minus-square,#opers .fa-minus-square').live('click',function(){
		$(this).parent().remove();
	});
	
	//页面中的分组器版本控件加载
	initGroupVersion();
})

/**
 * 页面中的select控件加载
 */
function initGroupVersion(){
	//分组器版本加载
	$.ajax({
		url:contextPath + "/systemConfig/getOnlineGroup.dhc",
		type:"get",
		async:false,
		success:function(result){
			var groupVersion = result.data.groupVersion;
			var str = "";
			if(groupVersion){
				for(var i in groupVersion){
					str += "<option value='"+groupVersion[i].VER_CODE+"'>"+groupVersion[i].VER_DESC+"</option>";
				}
			}
			$('#'+tabId+' .groupVersion').html(str);
		}
	})
}

/**
 * "手动录入"页面的拼接
 */
function initStep2manually(){
	var str = '';
	str += '<div style="max-width: 800px;padding:20px;margin:0 auto;border: 1px solid #ddd;';
	str += '    box-shadow: 0 5px 20px rgba(0,0,0,.2);overflow: hidden; margin-bottom: 20px;">';
	str += '  <table>';
	str += '  	<tr class="bg-info"><td colspan="4" class="title">基本信息</td></tr>';
	str += '  	<tr><td colspan="2" rowspan="3"><div style="width:100px;height:100%;border:1px solid #888;color:#888;text-align: center;float:right;font-size:20px;"><i class="fa fa-user fa-5x"></i></div></td>';
	str += '  		<td>病案号：</td>';
	str += '  		<td><input type="input" class="form-control" id="CASE_ID"></td>';
	str += '  	</tr>';
	str += '  	<tr>';
	str += '  		<td>性别：</td>';
	str += '  		<td style="text-align: left;">';
	str += '  			<input type="radio" class="form-control gender" name="gender" value="1" checked="checked">男&nbsp;&nbsp;&nbsp;&nbsp;';
	str += '  			<input type="radio" class="form-control gender" name="gender" value="2">女';
	str += '  		</td>';
	str += '  	</tr>';
	str += '  	<tr>';
	str += '  		<td>年龄：</td>';
	str += '  		<td><input type="number" class="form-control ue-animation" id="AGE" min="0" required="required"></td>';
	str += '  	</tr>';
	str += '  	<tr>';
	str += '  		<td width="150">住院天数：</td>';
	str += '  		<td width="120"><input type="number" class="form-control ue-animation" id="ACCTUAL_DAYS" min="0" required="required"></td>';
	str += '  		<td width="180">住院费用：</td>';
	str += '  		<td><input type="number" class="form-control ue-animation" id="TOTAL_EXPENSE" min="0" required="required"></td>';
	str += '  	</tr>';
	str += '  	<tr>';
	str += '  		<td>离院方式：</td>';
	str += '  		<td><select class="form-control" id="SF0108">';
	str += '  				<option value="1">医嘱离院</option>';
	str += '  				<option value="2">医嘱转院</option>';
	str += '  				<option value="3">医嘱转卫生服务机构或乡镇卫生院</option>';
	str += '  				<option value="4">非医嘱离院</option>';
	str += '  				<option value="5">死亡</option>';
	str += '  				<option value="9">其他</option>';
	str += '  			</select>';
	str += '  		</td>';
	str += '  		<td>新生儿年龄（天）：</td>';
	str += '  		<td><input type="number" class="form-control" id="SF0100" min="0"></td>';
	str += '  	</tr>';
	str += '  	<tr>';
	str += '  		<td>新生儿入院体重（克）：</td>';
	str += '  		<td><input type="number" class="form-control" id="SF0102" min="0"></td>';
	str += '  		<td>呼吸机使用时间（小时）：</td>';
	str += '  		<td><input type="number" class="form-control" id="SF0104" min="0"></td>';
	str += '  	</tr>';
	str += '  	<tr>';
	str += '  		<td>主要诊断编码：</td>';
	str += '  		<td><input type="input" class="form-control ue-animation" id="DISEASE_CODE" required="required"></td>';
	str += '  		<td>主要诊断名称：</td>';
	str += '  		<td><input type="input" class="form-control" id="DISEASE_NAME"></td>';
	str += '  	</tr>';
	str += '  	<tr class="bg-info">';
	str += '  		<td colspan="4" class="title">其他诊断<button onclick="addRow(\'diags\')" class="btn btn-default btn-xs pull-right">添加诊断</button></td>';
	str += '  	</tr>';
	str += '  	<tr>';
	str += '  		<td colspan="4" id="diags">';
	str += '  			<div class="form-inline">';
	str += '  				<span>诊断编码：</span>';
	str += '  				<input type="input" class="form-control code" style="margin:0;">';
	str += '  				<span>诊断名称：</span>';
	str += '  				<input type="input" class="form-control name" style="margin:0;">';
	str += '  				<i title="向上" class="fa fa-arrow-circle-up"></i>';
	str += '  				<i title="向下" class="fa fa-arrow-circle-down"></i>';
	str += '  				<i title="删除" class="fa fa-minus-square"></i>';
	str += '  			</div>';
	str += '  		</td>';
	str += '  	</tr>';
	str += '  	<tr class="bg-info">';
	str += '  		<td colspan="4" class="title">手术信息<button onclick="addRow(\'opers\')" class="btn btn-default btn-xs pull-right">添加手术</button></td>';
	str += '  	</tr>';
	str += '  	<tr>';
	str += '  		<td colspan="4" id="opers">';
	str += '  			<div class="form-inline">';
	str += '  				<span>手术编码：</span>';
	str += '  				<input type="input" class="form-control code" style="margin:0;">';
	str += '  				<span>手术名称：</span>';
	str += '  				<input type="input" class="form-control name" style="margin:0;">';
	str += '  				<i title="向上" class="fa fa-arrow-circle-up"></i>';
	str += '  				<i title="向下" class="fa fa-arrow-circle-down"></i>';
	str += '  				<i title="删除" class="fa fa-minus-square"></i>';
	str += '  			</div>';
	str += '  		</td>';
	str += '  	</tr>';
	str += '  	<tr class="bg-info">';
	str += '  		<td colspan="4" class="title">分组器版本</td>';
	str += '  	</tr>';
	str += '  	<tr>';
	str += '  		<td colspan="4">';
	str += '  			<div class="form-inline" style="text-align: left;">';
	str += '  				<span>分组器版本：</span>';
	str += '  				<select class="groupVersion form-control" style="margin:5px;" id="VER_CODE">';
	str += ' 				</select>';
	str += '  			</div>';
	str += '  		</td>';
	str += '  	</tr>';
	str += '  	<tr class="bg-info">';
	str += '  		<td colspan="4" class="title">ICD对照</td>';
	str += '  	</tr>';
	str += '  	<tr>';
	str += '  		<td colspan="4">';
	str += '  			<div class="form-inline" style="text-align: left;">';
	str += '  				<span>是否ICD对照：</span>';
	str += '  				<input type="radio" class="form-control" name="ICDStepOne" value="1">是&nbsp;&nbsp;&nbsp;&nbsp;';
	str += '  				<input type="radio" class="form-control" name="ICDStepOne" value="0" checked="checked">否';
	str += '  			</div>';
	str += '  		</td>';
	str += '  	</tr>';
	str += '  </table>';
	str += '  <button class="btn btn-primary pull-right" style="margin-left:10px;" onclick="doGroup(\'patient\')">开始分组</button>';
	str += '  <button class="btn btn-default pull-right" id="toStepUpperBtn" onclick="toStep1()">上一步</button>';
	str += '  <div class="panel panel-success" id="resultPanel" style="margin-top:50px;">';
	str += '		  <div class="panel-heading">分组结果</div>';
	str += '			  <div class="panel-body"></div>';
	str += '		  </div>';
	str += '</div>';
	$('#'+tabId+' #step2manually').html(str);
	$('#'+tabId+' #step2manually input:radio').iCheck({
		radioClass: 'iradio_square-blue',
	    increaseArea: '20%'
	});
	initGroupVersion();
}

function buildPatient(){
	patient = {};
	var diags = [];
	var opers = [];
	$('#step2manually table .form-control[id]').each(function(i,n){
		if(n.value!=''){
			patient[n.id] = n.value;
		}
	})
	patient['GENDER'] = $('div.checked input.gender').val();//性别
	
	//诊断
	$('#step2manually table #diags>div').each(function(){
		if ($(this).find('.code').val()!='') {
			diags.push($(this).find('.code').val());
			patient['DIAGS_CODE'] = diags;
		}
	})
	//手术
	$('#step2manually table #opers>div').each(function(){
		if ($(this).find('.code').val()!='') {
			opers.push($(this).find('.code').val());
			patient['OPERS_CODE'] = opers;
		}
		
	});
}

//获取首页数据导入进度并显示
function getMedicalRecordProgress(isExcel){
	timerStart();
	if(typeof(EventSource)!=='undefined'){
		var message='';
		var source=new EventSource($WEB_ROOT_PATH +'/GroupFunc/getProgress.dhc');
		source.onmessage=function(event){
			var info=JSON.parse(event.data)
			if(message!=info.msg){
				message=info.msg;
				$('#'+tabId+' #progress_info').append('<p>'+message+'</p>');
			}
			$('#'+tabId+' #progress_info_detail').html('<p>'+info.detail+'</p>');
			$('#'+tabId+' #progress_time').html(info.time);
			$('#'+tabId+' .progress-bar').css('width',info.percent+'%');
			$('#'+tabId+' .progress-bar span').html(info.percent+'%');
			if (info.msg=='已完成') {
				clearInterval(timerId);
				source.close();
				$('#'+tabId+' #progress_info').append('<p style="color:#5FBF18;"><i class="fa fa-smile-o fa-2x"></i></p>');
				$('#'+tabId+' #progress_info').append('<p></p>');
				$('#'+tabId+' #close_loading_btn').fadeIn();
				if(isExcel){
					getGroupResult();
				}
			}else if (info.msg=='已中断') {
				clearInterval(timerId);
				source.close();
				$('#'+tabId+' #progress_info').append('<p style="color:#FF4466;"><i class="fa fa-frown-o fa-2x"></i></p>');
				$('#'+tabId+' #progress_info').append('<p></p>');
				$('#'+tabId+' #close_loading_btn').fadeIn();
			}
			
		};
	}
}

function getGroupResult(){
	$.post(contextPath + '/fileUpload/getGroupResult.dhc').done(function(result){
		$('#step4 .panel').html(result.message);
	});
}

function addRow(clazz){
	var name='诊断';
	if (clazz=='opers') {
		name='手术';
	}
	$('#'+clazz).append('<div class="form-inline">'
			+'<span>'+name+'编码：</span>'
			+'<input type="input" class="form-control code">'
			+' <span>'+name+'名称：</span>'
			+'<input type="input" class="form-control name">'
			+'<i title="向上" class="fa fa-arrow-circle-up"></i>'
			+' <i title="向下" class="fa fa-arrow-circle-down"></i>'
			+' <i title="删除" class="fa fa-minus-square"></i>'
			+'</div>')
}

/**
 * @decription 从“选择系统病例”页面点击链接跳转到“手动录入”页面的显示
 * @param patientId  病例pmainindex
 * @param verCode    病组分组版本号
 */
function showPatient(patientId,verCode){
	$.ajax({
		url:contextPath+"/systemConfig/getConfigByCode.dhc",
		type:"post",
		data:{"alterParam":"MED_TYPE"},
		async:false,
		success:function(result){
			var patientVersion = result.data;
			$.post(contextPath + "/YiZhengHome/getPatientInfo.dhc", {patientId:patientId,patientversion:patientVersion})
			.done(function(result){
				var patient = result.data.patient;
				var maindiagnosis = result.data.maindiagnosis[0];
				var diagnosis = result.data.diagnosis;
				var operation = result.data.operation;
				var otherOperation = result.data.otherOperation;
				$('#'+tabId+' #CASE_ID').val(patient.P00050000.code);
				$('#'+tabId+' input:radio[name="gender"][value="'+patient.P00070001.code+'"]').iCheck('check');
				$('#'+tabId+' #AGE').val(patient.P00090000.code);
				$('#'+tabId+' #ACCTUAL_DAYS').val(patient.P00320000.code);//住院天数
				$('#'+tabId+' #TOTAL_EXPENSE').val(patient.P00800000.code);//住院费用
				$('#'+tabId+' #SF0108').val(patient.P00620001.code);//离院方式
				$('#'+tabId+' #SF0100').val(patient.NEWBORN_DAYS.code);//新生儿年龄（天）
				$('#'+tabId+' #SF0102').val(patient.P00120000.code);//新生儿入院体重（克）
				$('#'+tabId+' #SF0104').val(patient.P90120201.code);//呼吸机使用时间（小时）
				$('#'+tabId+' #DISEASE_CODE').val(maindiagnosis[1]);//主要诊断编码
				$('#'+tabId+' #DISEASE_NAME').val(maindiagnosis[0]);//主要诊断名称
				var str = '';
				//添加其他诊断
				for(var i=0;i<diagnosis.length;i++){
					str += '<div class="form-inline">';
					str += '	<span>诊断编码：</span>';
					str += '	<input type="input" class="form-control code" style="margin:0;" value="'+diagnosis[i][1]+'">';
					str += '	<span>诊断名称：</span>';
					str += '	<input type="input" class="form-control name" style="margin:0;" value="'+diagnosis[i][0]+'">';
					str += '	<i title="向上" class="fa fa-arrow-circle-up"></i>';
					str += '	<i title="向下" class="fa fa-arrow-circle-down"></i>';
					str += '	<i title="删除" class="fa fa-minus-square"></i>';
					str += '</div>';
				}
				$('#'+tabId+' #diags').html(str);
				//添加手术--------------------------------------------
				str = '';
				if($.isEmptyObject(operation)){
					str = '';
				}else{
					str += '<div class="form-inline">';
					str += '	<span>手术编码：</span>';
					str += '	<input type="input" class="form-control code" style="margin:0;" value="'+operation.OPER_M_CODE.code+'">';
					str += '	<span>手术名称：</span>';
					str += '	<input type="input" class="form-control name" style="margin:0;" value="'+operation.OPER_M_DESC.code+'">';
					str += '	<i title="向上" class="fa fa-arrow-circle-up"></i>';
					str += '	<i title="向下" class="fa fa-arrow-circle-down"></i>';
					str += '	<i title="删除" class="fa fa-minus-square"></i>';
					str += '</div>';
				}
				if(otherOperation.length>0){
					for(var i=0;i<otherOperation.length;i++){
						str += '<div class="form-inline">';
						str += '	<span>手术编码：</span>';
						str += '	<input type="input" class="form-control code" style="margin:0;" value="'+otherOperation[i].OPER_O_CODE.code+'">';
						str += '	<span>手术名称：</span>';
						str += '	<input type="input" class="form-control name" style="margin:0;" value="'+otherOperation[i].OPER_O_DESC.code+'">';
						str += '	<i title="向上" class="fa fa-arrow-circle-up"></i>';
						str += '	<i title="向下" class="fa fa-arrow-circle-down"></i>';
						str += '	<i title="删除" class="fa fa-minus-square"></i>';
						str += '</div>';
					}
				}
				$('#'+tabId+' #opers').html(str);
				//-------------------------------------------------------------
				$('#'+tabId+' #VER_CODE').val(verCode);//分组器版本
				
			});
		}
	})
}

/*
 * @param  flag 标记
 */
function toStep1(flag){
	if(flag){//如果标记存在，则上一步跳转到“选择系统病例”页面
		$('.step.current').removeClass('current');
		$('.step.one').removeClass('done').addClass('lastDone');
		$('section[id]').slideUp();
		$('#step2find').slideDown();
	}else{
		$('.step.current').removeClass('current');
		$('.step.one').removeClass('lastDone').addClass('current');
		$('section[id]').slideUp();
		$('#step1').slideDown();
	}
}

/**
 * @param  type      第2步跳转类型
 * @param  patientId 病例pmainindex
 * @param  verCode   病例分组版本
 * @param  flag      标记，若为1，则“上一步”跳转到“选择系统病例”页面
 */
function toStep2(type,patientId,verCode,flag){
	$('.step.one').removeClass('done').addClass('lastDone');
	$('.step.current').removeClass('current');
	$('.step.two').removeClass('lastDone').addClass('current');
	$('section[id]').slideUp();
	if(type=='manually'){
		initStep2manually();
		$('#step2manually').slideDown();
		if(patientId){
			showPatient(patientId,verCode);//如果是点击病案号过来的，就加载病例信息
		}
		if(flag==1){
			$('#'+tabId+' #toStepUpperBtn').unbind();
			$('#'+tabId+' #toStepUpperBtn').bind('click',function(){
				toStep1(flag);
			});
		}
		
	}else if(type=='excel'){
		$('#step2excel').slideDown();
	}else{
		$('#step2find').slideDown();
	}
}

/**
 * 
 * @param type excel文件分组--点击开始分组事件
 */
function toStep3(type){
	if (upf==0){
		drgUI.error("请选择上传文件！") ;
		return ;
	}else{
		$('.step.one').removeClass('lastDone').addClass('done');
		$('.step.two').removeClass('done').addClass('lastDone');
		$('.step.current').removeClass('current');
		$('.step.three').removeClass('lastDone').addClass('current');
		$('section[id]').slideUp();
		$('#step3').slideDown();
		groupVersion = $('#step2excel .groupVersion').val();
		//解析execl数据并分组
		$.post(contextPath + '/fileUpload/drgsGroup.dhc', {
			'groupVersion' : groupVersion,
			'isICDMatch':$('div.checked input[name="ICDStepTwo"]').val()
		}).done(function(data){
			if (data!=null){
				loadGroupResultTable(data.data);
			}
		});
	}
}
function toStep4(){
	$('.step.two').removeClass('lastDone').addClass('done');
	$('.step.three').removeClass('done').addClass('lastDone');
	$('.step.current').removeClass('current');
	$('.step.four').addClass('current');
	$('section[id]').slideUp();
	$('#step4').slideDown();
}

var timerId;
function timerStart(){
	var h = 0;
	var m = 0;
	var s = 0;
	timerId = setInterval(function(){
		s++;
		if (s==60) {
			s=0;
			m++;
		}
		if (m==60) {
			m=0;
			h++;
		}
		$('#'+tabId+' #progress_usedtime').html(h+':'+m+':'+s);
	}, 1000);
}

function doGroup(type){
	var isBlank=false;
	if (type=='patient') {
		//step1
		$.each($('input[required="required"]'),function(i,n){
			if($(n).val()==''){
				setTimeout(function(){
					$(n).removeClass('ue-shake');
				}, 900)
				$(n).addClass('ue-shake');
				isBlank=true;
			}
		});
		if(isBlank) return;
		$('#resultPanel .panel-body').html('<i class="fa fa-cog fa-spin fa-4x fa-fw margin-bottom text-success"></i>');
		groupVersion = $('#step2manually .groupVersion').val();
		buildPatient();
		$('#step2manually button').attr('disabled','disabled');
		$.post(contextPath + '/GroupFunc/drgsGroupPatients.dhc', {
			'patient': JSON.stringify(patient),
			'drgVersion' : groupVersion,
			'isICDMatch':$('div.checked input[name="ICDStepOne"]').val()
		}).done(function(data){
			//判断是否有错
			if(data.hasErrors){
				drgUI.error(data.errorMessage) ;
				$('#step2manually button').removeAttr('disabled');
				return;
			}
			$('#step2manually button').removeAttr('disabled');
			$('#resultPanel .panel-body').html('<div class="h4" id="groupResult"></div><div class="well" id="groupResultLog"></div>');
			var d = data.data;
			var result=[];
			if(d.DRG_CODE){
				if(d.DRG_DESC==null){
					d.DRG_DESC="无";
					d.DRGWEIGHT="";
					d.AVGDAYS="";
					d.AVGFEE="";
					d.RISKLEVEL="";
				}
//				$('#groupResult').html('DRG代码：'+d.DRG_CODE+'<br>DRG描述：'+d.DRG_DESC);
				var risklevel=getDicDesc("RiskLevel",d.RISKLEVEL)=='未定义'?"":getDicDesc("RiskLevel",d.RISKLEVEL);
				var str='DRGs代码：'+(d.DRG_CODE==undefined?"":d.DRG_CODE)+'<br>DRGs描述：'+(d.DRG_DESC==undefined?"":d.DRG_DESC)+'<br>权重：'+(d.DRGWEIGHT==undefined?"":d.DRGWEIGHT)+'<br>平均住院日：'+(d.AVGDAYS==undefined?"":d.AVGDAYS)+'<br>次均费用：'+(d.AVGFEE==undefined?"":d.AVGFEE)+'<br>风险等级：'+risklevel;
				$('#'+tabId+' #groupResult').html(str);
			}
			if(d.GROUP_LOG){
			    var s = '';
          	    var logs = d.GROUP_LOG;
          	    for (var i = 0; i < logs.length; i++) {
						s+=logs[i]+'\n'
				  }
				result.push('分组日志：\n'+s);
			}
			var i=0;
			var regn = /\n/;
			var timer = setInterval(function(){
				var codeArray = result.join('\n').split('');
				if (regn.test(codeArray[i])) {
					var br = document.createElement('br');
					$('#groupResultLog').append(br);
				}
				$('#groupResultLog').append(codeArray[i]);
				i++;
				
				if (i>codeArray.length) {
					clearInterval(timer);
				}
			}, 1);
		});
	}else if(type=='findAll'){
		//step3
		$('#resultGroup .panel-body').html('<i class="fa fa-cog fa-spin fa-4x fa-fw margin-bottom text-success"></i>');
		groupVersion = $('#step2find .groupVersion').val();
		GroupOnline();
	}
}

function loadGroupResultTable(data){
	toStep4();
	$('#'+tabId+' #resultTableDiv').html('<table class="table nowrap" id="resultTable"></table>');
	var columns = [
					{ "data": "CASE_ID","title":"病案号"},
					{ "data": "GENDER","title":"性别",
	                      "render": function(obj, type, full) {
	                    	  return getDicDesc('P00070001',full.GENDER);
	                      }
					},
					{ "data": "AGE","title":"年龄"},
					{ "data": "TOTAL_EXPENSE","title":"总费用(元)"},
					{ "data": "DISEASE_CODE","title":"主要诊断"},
					{ "data": "DRG_CODE","title":"DRGs代码",
                      "render": function(obj, type, full) {
                    	  var drgsCode = full.DRG_CODE;
                    	  var logStr = '';
                    	  var logs = full.GROUP_LOG;
                    	  if(logs){
                    		  for (var i = 0; i < logs.length; i++) {
                        		  logStr+=logs[i]+'\n';
    						  }
                        	  return '<span  title="分组日志：\n'+logStr+'">'+drgsCode+'</span>'
                    	  }
                    	  else{
                    		  return drgsCode;
                    	  }
                      }
					},
					{ "data": "DRG_DESC","title":"DRGs描述"},
					{ "data": "DRGWEIGHT","title":"病组权重"
					},{ "data": "AVGDAYS","title":"平均住院日(标杆)"
					},{ "data": "AVGFEE","title":"次均费用(标杆)"
					},{ "data": "RISKLEVEL","title":"风险等级(标杆)",
						 "render": function(obj, type, full) {
							 return getDicDesc("RiskLevel",full.RISKLEVEL)=='未定义'?"":getDicDesc("RiskLevel",full.RISKLEVEL);
						  } 
					}
                  ];
	var paramsDataTables={searching:false,paging:false,lengthChange:false,info:false,scrollX:false};
	$('#'+tabId+' #resultTable').dataTableBasic(columns, data,paramsDataTables);
	$('[data-toggle="tooltip"]').tooltip();
}

function loadPatientInfo(data){
	$('#'+tabId+' #resultOnLine').html('<table class="table nowrap" id="resultOnLineTable"></table>');
	oData=data;
	var columns = [
					{ "data": "MR_NO",title:"病案号",
						"render":function(obj,type,full){
							return '<a href="javascript:toStep2(\'manually\',\''+full.PATIENT_ID+'\',\''+full.VER_CODE+'\',1)">'+full.MR_NO+'</a>';
						}
					},
					{ "data": "NAME",title:"姓名"},
					{ "data": "SEX",title:"性别",
						"render": function(obj,type,full){
							return getDicDesc('P00070001',full.SEX);
						}
					},
					{ "data": "AGE",title:"年龄"},
					{ "data": "OUT_DATE",title:"出院日期"},
					{ "data": "IN_DAYS",title:"住院天数"},
					{ "data": "COST_SUM",title:"总费用"},
					{ "data": "OUT_WAY",title:"离院方式",
						"render": function(obj,type,full){
							return getDicDesc('P00620001',full.OUT_WAY);
						}
					},
					{ "data": "NEWBORN_DAY",title:"新生儿天数"},
					{ "data": "NEWBORN_W",title:"新生儿体重"},
					{ "data": "VENTILATOR_HOUR",title:"呼吸机使用时间"},
					{ "data": "DIACODE_MAIN",title:"主要诊断编码"},
					{ "data": "DIA_MAIN",title:"主要诊断"},
					{ "data": "DIA_OTHER",title:"其他诊断及其描述"},
					{ "data": "OPER_MAIN",title:"主要手术及其描述"},
					{ "data": "OPER_OTHER",title:"其他手术及其描述"},
					{ "data": "DRG_CODE",title:"DRG代码"},
					{ "data": "DRG_DESC",title:"DRG描述"}
                ]
	var paramsDataTables={paing:false,searching:false,ordering:false,scrollX:true};
	$('#'+tabId+' #resultOnLineTable').dataTableBasic(columns, data,paramsDataTables);
}
function InsertResult(){
	$.post(contextPath + '/GroupFunc/replaceGroupResult.dhc',{
		'doInsert':'yes'
	}).done(function(data){
		if(data=='1'){
			drgUI.success("更新成功") ;
		}else{
			drgUI.error("更新失败") ;
		}
	});
}
var timerId;
function timerStart(){
	var h = 0;
	var m = 0;
	var s = 0;
	timerId = setInterval(function(){
		s++;
		if (s==60) {
			s=0;
			m++;
		}
		if (m==60) {
			m=0;
			h++;
		}
		$('#'+tabId+' #progress_usedtime').html(h+':'+m+':'+s);
	}, 1000)
}
//根据病案号查询系统中病例信息
function findDataInDatabase(){
	mrId=$('#step2find #findInSystem').val();
	mrId=mrId.replace(/,/g,"','");
	mrId=mrId.replace(/，/g,"','");
	$.post(contextPath + '/GroupFunc/findPatientInDatabase.dhc',{
		'mrId':mrId
	}).done(function(data){
		//加载分组器版本，为所有查询出来的病例信息的最新分组器版本
		var verCode;
		var verCodeArr = [];
		for( var o in data){
			verCodeArr.push(data[o].VER_CODE)
		}
		verCodeArr.reverse();
		verCode = verCodeArr[0];
		$('#'+tabId+' #VER_CODE_find').val(verCode);
		loadPatientInfo(data);
		
	});
}
function GroupOnline(){
	groupVersion = $('#'+tabId+' #step2find .groupVersion').val();
	mrId=$('#'+tabId+' #step2find #findInSystem').val();
	mrId=mrId.replace(/,/g,"','");
	mrId=mrId.replace(/，/g,"','");
	$.post(contextPath + '/GroupFunc/findAndGroupPatient.dhc',{
		'mrId':mrId,
		'drgVersion':groupVersion,
		'isICDMatch':$('#'+tabId+' div.checked input[name="ICDStepThree"]').val()
	}).done(function(data){
		if(data.hasErrors){
			drgUI.error(data.errorMessage) ;
			$('#'+tabId+' #step2manually button').removeAttr('disabled');
			return;
		}
		var data=data.data;
		$('#'+tabId+' #step2find button').removeAttr('disabled');
		$('#'+tabId+' #resultGroup .panel-body').html('<div class="h4" id="groupingResult"></div><div class="well" id="groupingLog"></div>');
		if(data.length>0){	
		var stri="";
		var result=[];
		for(var o=0;o<data.length;o++){
			var d = data[o];
			if(d.New_DRG_CODE){
				if(d.New_DRG_DESC==null){
					d.DRG_DESC="无";
					d.DRGWEIGHT="";
					d.AVGDAYS="";
					d.AVGFEE="";
					d.RISKLEVEL="";	
				}
				var risklevel=getDicDesc("RiskLevel",d.RISKLEVEL)=='未定义'?"":getDicDesc("RiskLevel",d.RISKLEVEL);
				
				stri=stri+'<br>病案号为'+d.MR_NO+',出院日期为'+d.OUT_DATE+'的病例在线分组结果为：<br>'+(d.New_DRG_CODE==undefined?"":d.New_DRG_CODE)+'['+(d.New_DRG_DESC==undefined?"":d.New_DRG_DESC)+']<br>权重：'+(d.DRGWEIGHT==undefined?"":d.DRGWEIGHT)+'<br>平均住院日：'+(d.AVGDAYS==undefined?"":d.AVGDAYS)+'<br>次均费用：'+(d.AVGFEE==undefined?"":d.AVGFEE)+'<br>风险等级：'+risklevel+'<br>';
//				stri=stri+'<br>病例ID为'+d.CASE_ID+'的在线分组结果为：<br>'+d.New_DRG_CODE+'['+d.New_DRG_DESC+']<br>';
				if(d.Old_Drgs_Code!=null){
					stri=stri+'系统中分组结果为：<br>'+d.Old_Drgs_Code+'['+d.Old_Drgs_Desc+']';	
				}else{
					stri=stri+'系统中分组结果为：未入组<br>';
				}
				
				$('#'+tabId+' #groupingResult').html(stri);
			}
			if(d.GROUP_LOG){
			    var s = '';
	      	    var logs = d.GROUP_LOG;
	      	    for (var i = 0; i < logs.length; i++) {
						s+=logs[i]+'\n'
				  }
	      	  result.push('病案号为'+d.MR_NO+',出院日期为'+d.OUT_DATE+'的病例的分组日志：\n'+s);
			}
			var i=0;
			var regn = /\n/;
			var timer = setInterval(function(){
				var codeArray = result.join('\n').split('');
				if (regn.test(codeArray[i])) {
					var br = document.createElement('br');
					$('#'+tabId+' #groupingLog').append(br);
				}
				$('#'+tabId+' #groupingLog').append(codeArray[i]);
				i++;
				
				if (i>codeArray.length) {
					clearInterval(timer);
				}
			}, 1);	
		}
		}
	});

}